var apiHost = wx.getStorageSync('apiHost');   //调用接口请求地址
var yunId = wx.getStorageSync('yunId');                //云id
var openId = wx.getStorageSync('openId');              //openId

var apiUpLoad = wx.getStorageSync('apiUpLoad');        //上传外网图片地址

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],                 //上传照片list
    uploadImg : [],           //上传照片
    objectArray:[],           //初始化商品分类
    toState: "保存到下架商品", //商品状态提示消息
    cateGoryId : '',          //分类id
    hiddenLoading: true,      //显示隐藏loading
    goodsDetail:[],           //商品详情集合
    index:'',                 //上传照片flag
    spuId:'',                 //商品id
    state: "",                //商品状态
    isSpecial : ''           //是否特卖
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      var that = this;
      that.cateGoryList();    //初始化商品分类

      var spuId = options.spuId;
      var downGoods = options.flag; //从下架商品跳转过来的

      if (downGoods != undefined){
        that.setData({
          downGoods: downGoods
        })
      }

      if (spuId != undefined) {
        that.goodsDetail(spuId);//编辑初始化商品
      }
      
  },
  //编辑初始化商品
  goodsDetail: function (spuId){
    //显示加载动画
    this.setData({
      hiddenLoading: false
    });

    var that = this;
    wx.request({
      url: apiHost + "xcx/goods/editDetail",
      data: {
          spuId: spuId
      },
      header: {
          'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var goodsDetail = res.data.data;
          that.setData({
            goodsDetail: goodsDetail,
            spuId: goodsDetail.spuId,
            hiddenLoading: true,
            imgs: goodsDetail.images
          });
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    });
  },
  //商品上架或下架
  switch1Change: function (e) {
    // 判断是否打开
    if (e.detail.value) {
      this.setData({
        toState: "上架中",
        state: "1"
      });
    } else {
      this.setData({
        toState: "保存到下架商品",
        state: "0"
      });
    }
  },

  //商品是否特卖
  switch2Change: function (e) {
    // 判断是否打开
    if (e.detail.value) {
      this.setData({
        isSpecial: "1"
      });
    } else {
      this.setData({
        isSpecial: "0"
      });
    }
  },
  /**
   * 上传图片
   */
  uploadImg : function(){

    var that = this; 

    wx.chooseImage({
      count: 6, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        var imgs = that.data.imgs;
        for (var i = 0; i < tempFilePaths.length; i++) {
          that.upload(that, tempFilePaths[i]);
        }
      }
    })
  },
  //商品图片传送到外网
  upload: function (page, path) {

    var that = this; 

    wx.showToast({
      icon: "loading",
      title: "正在上传"
    }),
      wx.uploadFile({
        // url: "http://file.jhjvip.cn:8888/image-server/uploadImage/oss",
        url: apiUpLoad+"image-server/uploadImage/oss",
        filePath: path,
        name: 'file',
        header: { "Content-Type": "multipart/form-data" },
        formData: {
          //和服务器约定的token, 一般也可以放在header中
          'session_token': wx.getStorageSync('session_token')
        },
        success: function (res) {
          var imgs = that.data.imgs;
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
          var data = res.data

          var aa = page.stringToJson(data);  //字符串转json

          var imgUrl = aa.data.url;

          imgs.push(imgUrl);

          page.setData({  //上传成功修改显示头像
            imgUrl: imgUrl,
            imgs: imgs
          })
        },
        fail: function (e) {
          console.log(e);
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        },
        complete: function () {
          wx.hideToast();  //隐藏Toast
        }
      })
  },
  //删除上传照片
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },

  //初始化分类list
  cateGoryList : function(){
    var that = this ; 
    wx.request({
      url: apiHost + "xcx/category/list",
      data: {
        yunId: yunId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var objectArrays = res.data.data;
          that.setData({
            objectArray: objectArrays
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    });
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  //添加分类方法
  addCategoryModel: function () {
    var that = this;

    that.setData({
      showModal: true,
      isAdd: true,
      cateGoryId: '',        //分类id
      onclickCon: "onConfirm"
    });
  },
  //新建分类 确认 表单提交
  addCateGoryBox: function (e) {
    var that = this;
    var cateName = e.detail.value.name; //分类名称
    var cateGoryId = that.data.cateGoryId;              //分类id

    if (cateGoryId == '') {
      that.addOrDetailCategory(cateName, '');
    } else {
      that.addOrDetailCategory(cateName, cateGoryId);
    }
  },
  /**
   * 添加分类方法
   * @param cateName   分类名称
   */
  addOrDetailCategory: function (cateName, cateGoryId) {

    var that = this;

    wx.request({
      url: apiHost + 'xcx/category/addOrEdit',
      data: {
        yunId: yunId,
        openId: openId,
        name: cateName,
        categoryId: cateGoryId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          that.onCancel();//关闭对话框
          that.cateGoryList();
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      },
    })
  },
  //表单提交
  formSubmit: function (e) {
    var that = this;
    var formData = e.detail.value;                 //表单提交的整体json
    var spuId = that.data.spuId ;                 //spuId

    //判断是添加 还是编辑
    if(spuId==''){
        that.addOrDetail(formData,'add')
    }else{
        that.addOrDetail(formData,'edit')
    }
  },

  //添加或编辑商品
   addOrDetail : function(formData,flag){
       var that = this;
       var goodName = formData.goodName;             //商品名称
       var categoryId = formData.categoryId;         //商品类型Id
       var goodImages = formData.goodImages;         //商品图片 例子:1,2,3

       var originPrice = formData.originPrice;       //商品原价
       var price = formData.price;                    //商品价格
       var inventory = formData.inventory;           //库存
       var threshold = formData.threshold;            //预警值
       var state = formData.state;                   //上架下架状态
       var spuId = that.data.spuId ;                 //spuId
       var isSpecial = that.data.isSpecial
 
       var information = "";

       if (goodName === "" || goodName === null) {
           information = "请填写商品名称";
       } else if (categoryId === "" || categoryId === null) {
           information = "请选择商品分类";
       } else if (goodImages === "" || goodImages === null) {
           information = "请上传商品图片";
       } else if (originPrice === "" || originPrice === null) {
           information = "请填写商品原价";
       } else if (price === "" || price === null) {
           information = "请填写商品价格";
       } else if (inventory === "" || inventory === null) {
           information = "请填写商品库存";
       } else if (threshold === "" || threshold === null) {
           information = "请填写预警库存";
       }
       if (information != "") {
           that.setData({
               msg: information,
               showQueModal: true,
           });
       }
       if (that.data.showQueModal) {
           return;
       }

       wx.showLoading({
         title: '加载中',
         icon: 'loading',
       });

       wx.request({
           url: apiHost + "xcx/goods/"+flag,
           data: {
               openId: openId,
               yunId: yunId,
               spuId : spuId,
               goodName: goodName,
               categoryId: categoryId,
               goodImages: goodImages,
               originPrice: originPrice,
               price: price,
               inventory: inventory,
               threshold: threshold,
               state: state,
               isSpecial: isSpecial
           },
           header: {
               'content-type': 'application/json' // 默认值
           },
           success: function (e) {

               if(e.data.code=="10000"){

                  wx.hideLoading();   //隐藏加载loading

                   var toFlag = that.data.downGoods;
                   //指定跳转
                   if (toFlag =='down'){
                     wx.navigateTo({
                       url: '../downGoods/downGoods'
                     });
                   }else if (toFlag == 'threshold') {
                     wx.navigateTo({
                       url: '../thresholdGoods/thresholdGoods'
                     });
                   } else{
                     wx.navigateTo({
                       url: '../shopIndex/shopIndex'
                     });
                   }
               }else{
                   that.setData({
                       msg: e.data.msg,
                       showQueModal: true,
                   });
               }
           }
       });
   },

   //删除商品 (确认弹窗)
   delGoods : function(){
       var that = this;
       that.setData({
         showModalDel: true,
       });
   },

   //删除商品
   queDel:function(){
     var that = this;
     var spuId = that.data.spuId;                 //spuId

     wx.showLoading({
       title: '加载中',
       icon: 'loading',
     });
     wx.request({
       url: apiHost + 'xcx/goods/del',
       data: {
         yunId: yunId,
         openId: openId,
         spuId: spuId
       },
       header: {
         'content-type': 'application/json' // 默认值
       },
       success: function (res) {
         var code = res.data.code;
         var msg = res.data.msg

         if (code == "10000") {
           wx.hideLoading();   //隐藏加载loading
           wx.navigateTo({
             url: '../shopIndex/shopIndex'
           });
         }else{
           wx.showToast({
             title: msg,
             icon: 'none',
             duration: 2000,
             mask: true
           });
         }
       },
     })
   },

  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  hideQueModal: function () {
    this.setData({
      showQueModal: false
    });
  },
  hideDelModal: function () {
    this.setData({
      showModalDel: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  onQueCancel: function () {
    this.hideQueModal();
  },
  onCancelDel: function () {
    this.hideDelModal();
  },
  /**
    *字符串转json
    */
  stringToJson: function (data) {
    return JSON.parse(data);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

})